<template>
    <div class="category-container">
        <el-row :gutter="20">
            <el-col :span="6">
                <el-card class="box-card">
                    <el-tree
                        :expand-on-click-node="false"
                        node-key="catId"
                        :check-strictly="true"
                        show-checkbox
                        :data="categories"
                        :props="defaultProps"
                        :default-expanded-keys="expandedNode"
                        @node-click="categoryClick">
                        <template #default="{ node, data }">
                            <span class="custom-tree-node">
                              <span>{{ node.label }}</span>
                              <span>
                                  <a v-show="data.catLevel !== 3" @click.stop="showAddCategory(node, data)">新增</a>
                                  <a v-show="data.catLevel === 3" @click.stop="delCategory(node, data)">删除</a>
                              </span>
                            </span>
                        </template>
                    </el-tree>
                </el-card>
            </el-col>
            <el-col :span="18">
                <el-card class="box-card">
                    <el-form :inline="true">
                        <el-row>
                            <el-form-item>
                                <el-input
                                    placeholder="请输入内容"
                                    v-model="key"
                                    clearable>
                                </el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button>查询</el-button>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="success" @click="showAddAttrGroup">新增</el-button>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="danger" @click="batchDelete">批量删除</el-button>
                            </el-form-item>
                        </el-row>
                        <el-row>
                            <el-table
                                :data="attrData"
                                @selection-change="handleSelectionTableChange"
                                ref="multipleTable"
                                border
                                style="width: 100%">
                                <el-table-column
                                    type="selection"
                                    width="55">
                                </el-table-column>
                                <el-table-column
                                    prop="attrGroupId"
                                    label="分组id">
                                </el-table-column>
                                <el-table-column
                                    prop="attrGroupName"
                                    label="组名">
                                </el-table-column>
                                <el-table-column
                                    prop="sort"
                                    label="排序">
                                </el-table-column>
                                <el-table-column
                                    prop="descript"
                                    label="描述">
                                </el-table-column>
                                <el-table-column
                                    label="组图标">
                                    <template slot-scope="scope">
                                        <i :class="scope.row.icon"></i>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    fixed="right"
                                    label="操作"
                                    width="100">
                                    <template #default="scope">
                                        <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button>
                                        <el-button type="text" size="small">编辑</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-row>
                        <el-row style="margin-top: 20px;text-align: right;">
<!--                            <el-pagination-->
<!--                                :page-sizes="[10, 20, 30, 50]"-->
<!--                                :page-size="100"-->
<!--                                layout="total, sizes"-->
<!--                                :total="400">-->
<!--                            </el-pagination>-->
                        </el-row>
                    </el-form>
                </el-card>
            </el-col>
        </el-row>

        <el-dialog title="新增分类"
                   width="400px"
                   :append-to-body="true"
                   :visible.sync="categoryFormVisible">
            <el-form :model="category">
                <el-form-item label="分类名称">
                    <el-input v-model="category.name"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                  <el-button @click="categoryFormVisible = false">取 消</el-button>
                  <el-button type="primary" @click.prevent="addCategory">确 定</el-button>
                </span>
            </template>
        </el-dialog>


        <el-dialog title="新增组属性"
                   width="400px"
                   :append-to-body="true"
                   :visible.sync="attrGroupFormVisible">
            <el-form :model="attrGroup" label-position="right" label-width="80px">
                <el-form-item label="名称：">
                    <el-input v-model="attrGroup.attrGroupName"></el-input>
                </el-form-item>
                <el-form-item label="排序：">
                    <el-input v-model="attrGroup.sort"></el-input>
                </el-form-item>
                <el-form-item label="描述：">
                    <el-input v-model="attrGroup.descript"></el-input>
                </el-form-item>
                <el-form-item label="图标：">
                    <e-icon-picker v-model="attrGroup.icon"/>
                </el-form-item>
                <el-form-item label="分类id：">
                    <el-cascader
                        v-model="cateValueId"
                        :options="options"
                        :props="props"
                        @change="propsChange"></el-cascader>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                  <el-button @click="attrGroupFormVisible = false">取 消</el-button>
                  <el-button type="primary" @click.prevent="addAttrGroup">确 定</el-button>
                </span>
            </template>
        </el-dialog>

    </div>
</template>

<script>
    import {
        addAttrGroup,
        addCategory,
        batchDelCategory,
        delCategory,
        getAttrGroups,
        getTreeCategories
    } from "../../api/category";

    export default {
        name: "index",
        data() {
            return {
                key: '',                // 条件查询key
                categories: [],         // 封装所有分类信息
                defaultProps: {         // 映射分类属性显示
                    children: 'childrens',
                    label: 'name'
                },
                attrData: [],           // 表单组属性数据
                categoryFormVisible: false,     // 分类对话框
                attrGroupFormVisible: false,    // 组属性对话框
                category: {             // 分类对象
                    name: '',
                    parentCid: '',
                    catLevel: '',
                    showStatus: 1,
                    sort: 0
                },
                attrGroup: {            // 组属性对象
                    attrGroupId: null,
                    attrGroupName: '',
                    sort: 0,
                    descript: '',
                    icon: '',
                    catelogId: 0
                },
                expandedNode: [],       // 分类展开的节点（分类id数组）
                catelogId: 0,           // 分类id（用于查询三级分类下的组属性数据）
                options: [],            // 组属性对话框回显分类数据（和categories一样）
                cateValueId: "",        // 组属性对话框存放分类id
                props: {                // 组属性对话框级联选择器属性映射
                    "label": "name",
                    "value": "catId",
                    "children": "childrens"
                },
                multipleTable: []       // 批量删除组属性数据（组属性id数组）
            }
        },
        created() {
            this.loadCategories();
        },
        methods: {
            handleClick(row) {
                console.log(row);
            },
            /* 加载分类tree结构数据 */
            loadCategories() {
                getTreeCategories().then(res => {
                    this.categories = res.data.data;
                    this.options = res.data.data;
                })
            },
            /* 新增节点显示弹窗 */
            showAddCategory(node, data) {
                this.categoryFormVisible = true;
                this.category.catLevel = data.catLevel + 1;
                this.category.parentCid = data.catId;
            },
            /* 新增分类 */
            addCategory() {
                console.log('新增对象：',this.category);
                addCategory({
                    'name': this.category.name,
                    'parentCid': this.category.parentCid,
                    'catLevel': this.category.catLevel,
                    'showStatus': this.category.showStatus,
                    'sort': this.category.sort
                }).then(res => {
                    if(res.data.code === 0) {
                        this.$message({
                            message: res.data.msg,
                            type: 'success'
                        })
                        this.categoryFormVisible = false;
                        this.loadCategories();
                        this.expandedNode = [this.category.parentCid];
                    }else {
                        this.$message.error(res.data.msg);
                    }
                }).catch(() => {
                    this.$message.error('新增失败')
                })
            },
            /* 删除分类事件 */
            delCategory(node, data) {
                this.$confirm(`是否删除【${data.name}】分类?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    delCategory({
                        "id": data.catId
                    }).then(res => {
                        this.$message({
                            type: 'info',
                            message: res.data.msg
                        });
                        this.loadCategories();
                        this.expandedNode = [data.parentCid];
                    })
                }).catch(error => {
                    this.$message({
                        type: 'info',
                        message: error
                    });
                });
            },
            /* 分类点击事件 */
            categoryClick(data) {
                if(data.catLevel === 3) {
                    console.log(data.catId);
                    this.catelogId = data.catId;
                    this.getAttrGroups();
                }
            },
            /* 获取三级分类下的平台属性 */
            getAttrGroups() {
                getAttrGroups({
                    "key": this.key,
                    "catelogId": this.catelogId
                },).then(res => {
                    this.attrData = res.data.data;
                }).catch(error => {
                    console.error(error);
                })
            },
            /* 显示新增属性分组对话框 */
            showAddAttrGroup() {
                this.attrGroupFormVisible = true;
                // this.attrGroup.catelogId = this
            },
            /* 新增分组属性 */
            addAttrGroup() {
                this.attrGroup.catelogId = this.cateValueId[this.cateValueId.length-1];
                addAttrGroup(
                    this.attrGroup
                ).then(res => {
                    this.$message({
                        type: 'info',
                        message: res.data.msg
                    });
                    this.attrGroupFormVisible = false;
                    if(this.catelogId !== 0){
                        this.getAttrGroups();
                    }
                }).catch(() => {
                    this.$message.error("系统异常");
                })
            },
            /* 级联选择器改变事件 */
            propsChange(val) {
                this.attrGroup.catelogId = val[val.length-1];   // 选中的分类id
            },
            /* 选中表数据事件 */
            handleSelectionTableChange(val) {
                this.multipleTable = val;
            },
            /* 批量删除事件 */
            batchDelete() {
                if(this.multipleTable.length === 0) {
                    this.$message.error("请先选中要删除的组属性！");
                }else{
                    let temp = this.multipleTable;
                    let ids = [];
                    temp.forEach((val) => {
                        ids.push(val.attrGroupId);
                    });
                    batchDelCategory(
                        ids
                    ).then(res => {
                        this.$message({
                            type: 'info',
                            message: res.data.msg
                        });
                        this.getAttrGroups();
                    }).catch(() => {
                        this.$message.error("系统异常");
                    })
                }
            }
        }
    }
</script>

<style scoped>
    .custom-tree-node a{
        margin-left: 10px;
        color: dodgerblue;
        font-size: 15px;
    }
</style>
